package cn.iocoder.yudao.module.handguard.controller.app.user;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.handguard.controller.admin.banner.vo.BannerRespVO;
import cn.iocoder.yudao.module.handguard.controller.admin.client.vo.UserAddReqsVo;
import cn.iocoder.yudao.module.handguard.controller.admin.client.vo.UserAllocationReqVo;
import cn.iocoder.yudao.module.handguard.controller.admin.homeone.vo.HomeOneRespVO;
import cn.iocoder.yudao.module.handguard.controller.admin.hometwo.vo.HomeTwoRespVO;
import cn.iocoder.yudao.module.handguard.controller.admin.journalism.vo.JournalismRespVO;
import cn.iocoder.yudao.module.handguard.controller.admin.product.vo.ProductRespVO;
import cn.iocoder.yudao.module.handguard.controller.admin.productaccess.vo.ProductAccessResVO;
import cn.iocoder.yudao.module.handguard.controller.admin.productaccess.vo.ProductAccessRespVO;
import cn.iocoder.yudao.module.handguard.controller.admin.publicitytype.vo.PublicitySelectBaseVO;
import cn.iocoder.yudao.module.handguard.controller.admin.publicitytype.vo.PublicitySelectReqsVO;
import cn.iocoder.yudao.module.handguard.controller.admin.publicitytype.vo.PublicityTypeRespVO;
import cn.iocoder.yudao.module.handguard.controller.app.user.vo.*;
import cn.iocoder.yudao.module.handguard.convert.banner.BannerConvert;
import cn.iocoder.yudao.module.handguard.convert.homeone.HomeOneConvert;
import cn.iocoder.yudao.module.handguard.convert.hometwo.HomeTwoConvert;
import cn.iocoder.yudao.module.handguard.convert.journalism.JournalismConvert;
import cn.iocoder.yudao.module.handguard.convert.product.ProductConvert;
import cn.iocoder.yudao.module.handguard.convert.productaccess.ProductAccessConvert;
import cn.iocoder.yudao.module.handguard.convert.user.MiniUserConvert;
import cn.iocoder.yudao.module.handguard.dal.dataobject.banner.BannerDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.homeone.HomeOneDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.hometwo.HomeTwoDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.journalism.JournalismDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.product.ProductDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.productaccess.ProductAccessDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.user.UserDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userfollowup.UserFollowUpDO;
import cn.iocoder.yudao.module.handguard.dal.mysql.user.MiniUserMapper;
import cn.iocoder.yudao.module.handguard.properties.WxLoginVo;
import cn.iocoder.yudao.module.handguard.service.banner.BannerService;
import cn.iocoder.yudao.module.handguard.service.homeone.HomeOneService;
import cn.iocoder.yudao.module.handguard.service.hometwo.HomeTwoService;
import cn.iocoder.yudao.module.handguard.service.journalism.JournalismService;
import cn.iocoder.yudao.module.handguard.service.order.OrderService;
import cn.iocoder.yudao.module.handguard.service.publicitytype.PublicityTypeService;
import cn.iocoder.yudao.module.handguard.service.user.MiniUserService;
import cn.iocoder.yudao.module.handguard.service.userfollowup.UserFollowUpService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;

/**
 * @author: liuweijun
 * @since: 2023/9/11 16:43
 * @description:
 */

@Tag(name = "小程序 - 用户")
@RestController
@RequestMapping("/mini")
@Validated
public class MiniUserController {

    @Resource
    private MiniUserService miniUserService;

    @Resource
    private MiniUserMapper miniUserMapper;

    @Resource
    private BannerService bannerService;

    @Resource
    private HomeOneService homeOneService;

    @Resource
    private HomeTwoService homeTwoService;

    @Resource
    private JournalismService journalismService;

    @Resource
    private OrderService orderService;

    @Resource
    private UserFollowUpService followUpService;

    @Resource
    private PublicityTypeService publicityTypeService;


    @PostMapping("/auth/login")
    @Operation(summary = "用户登录")
    @PermitAll
    public CommonResult<AuthLoginRespVo> callback(@RequestBody WxLoginVo wxLoginVo) {
        return miniUserService.login(wxLoginVo);
    }

    @PostMapping("/auth/getUserInfo")
    @Operation(summary = "获取当前用户信息")
    public CommonResult<UserPropertyBaseVO> authGetUserInfo() {
        Long userId = getLoginUser().getId();
        return miniUserService.authGetUserInfo(userId);
    }

    @PostMapping("/addReference")
    @Operation(summary = "用户-添加推荐人")
    public CommonResult<String> addReference(@RequestBody PhoneParamVo paramVo) {
        //当前用户id
        //Long userId = getLoginUser().getId();
        //LambdaQueryWrapper<UserDO> queryWrapper = new LambdaQueryWrapper<>();
        //queryWrapper.eq(UserDO::getMobile,paramVo.getPhone());
        ////推荐人
        //UserDO referrerUser = miniUserMapper.selectOne(queryWrapper);
        //if (referrerUser!=null){
        //    LambdaQueryWrapper<UserDO> wrapper = new LambdaQueryWrapper<>();
        //    wrapper.eq(UserDO::getId,userId);
        //    //绑定推荐人
        //    UserDO user = miniUserMapper.selectOne(wrapper);
        //    user.setReferrer(referrerUser.getId());
        //    miniUserMapper.updateById(user);
        //    return CommonResult.success("操作成功");
        //}else {
        //    return CommonResult.error(500,"没有找到推荐人信息");
        //}
        return CommonResult.success("");
    }




    @GetMapping("/banner/list")
    @Operation(summary = "banner列表")
    @PermitAll
    public CommonResult<List<BannerRespVO>> getBannerList(Integer bannerType) {
        List<BannerDO> list = bannerService.getBannerList(bannerType);
        List<BannerRespVO> bannerRespVOList = BannerConvert.INSTANCE.convertList(list);
        return success(bannerRespVOList);
    }


    @GetMapping("/cjgd/list")
    @Operation(summary = "首页成交榜-滚动数据列表")
    @PermitAll
    public CommonResult<List<HomeOneRespVO>> getHomeOneList() {
        List<HomeOneDO> list = homeOneService.getHomeOneList();
        return success(HomeOneConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/cjyh/list")
    @Operation(summary = "首页成交榜-用户数据列表")
    @PermitAll
    public CommonResult<List<HomeTwoRespVO>> getHomeTwoList() {
        List<HomeTwoDO> list = homeTwoService.getHomeTwoList();
        return success(HomeTwoConvert.INSTANCE.convertList(list));
    }


    @GetMapping("/agent/list")
    @Operation(summary = "首页-推荐业务员列表")
    @PermitAll
    public CommonResult<List<AgentResVo>> getAgentList() {
        List<AgentResVo> agentResVos=  new ArrayList<>();
        LambdaQueryWrapper<UserDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserDO::getUserType,"2");
        queryWrapper.eq(UserDO::getStatus,0);
        queryWrapper.orderByDesc(UserDO::getCreateTime);
        List<UserDO> userDOList = miniUserMapper.selectList(queryWrapper);
        for (UserDO userDO :userDOList){
            AgentResVo agentResVo  = new AgentResVo();
            BeanUtils.copyProperties(userDO,agentResVo);
            agentResVos.add(agentResVo);
        }
        return success(agentResVos);
    }

    @GetMapping("/agent/productList")
    @Operation(summary = "业务员-推荐产品列表")
    public CommonResult<List<ProductRespVO>> getAgentProductList() {
        //当前用户id
        Long userId = getLoginUser().getId();
        List<ProductDO> productDOList = miniUserService.getAgentProductList(userId);
        return success(ProductConvert.INSTANCE.convertList(productDOList));
    }


    @GetMapping("/news/list")
    @Operation(summary = "首页-新闻资讯")
    @PermitAll
    public CommonResult<List<JournalismRespVO>> getJournalismList() {
        List<JournalismDO> list = journalismService.getJournalismList();
        return success(JournalismConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/news/info")
    @Operation(summary = "首页-新闻资讯详情")
    @PermitAll
    public CommonResult<JournalismRespVO> getJournalism(@RequestParam("id") Long id) {
        JournalismDO journalism = journalismService.getJournalism(id);
        return success(JournalismConvert.INSTANCE.convert(journalism));
    }

    @GetMapping("/getMiRecommend")
    @Operation(summary = "我的推荐")
    public CommonResult<List<UserRecommendBaseVO>> getMiRecommend(@RequestParam("type") String type) {
        Long userId = getLoginUser().getId();
        List<UserDO> userDOList = new ArrayList<>();
        LambdaQueryWrapper<UserDO> wrapper = new LambdaQueryWrapper<>();
        if (type.equals("1")) {
            //wrapper.eq(UserDO::getReferrer,userId);
            //userDOList = miniUserMapper.selectList(wrapper);
             userDOList =  miniUserMapper.selectUserReferrerListByUserId(userId);
        }else {
            UserDO user = miniUserMapper.getUserInfo(userId);
            UserDO userDO= miniUserMapper.getUserInfo(user.getReferrer());
            if (userDO != null) {
                userDOList.add(userDO);
            }
        }

        return success(MiniUserConvert.INSTANCE.convertRList(userDOList));
    }

    @GetMapping("/getWarrantMyFollowUpUser")
    @Operation(summary = "业务员、权证-总待跟进客户")
    public CommonResult<Integer> getMyFollowUpUser() {
        //当前用户id
        Long userId = getLoginUser().getId();
        LambdaQueryWrapper<UserDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserDO::getId,userId);
        UserDO userDO = miniUserMapper.selectOne(queryWrapper);
        int number = 0;
        if (userDO.getUserType().equals("2")){
            number = followUpService.getMyFollowUpUser(userId,2);
        }else if (userDO.getUserType().equals("3")){
            number = followUpService.getMyFollowUpUser(userId,3);
        }
        return success(number);
    }

    @GetMapping("/getMyMonthFollowUpUser")
    @Operation(summary = "业务员、权证当月已跟进用户")
    public CommonResult<Integer> getAgentMyFollowUpUser() {
        //当前用户id
        Long userId = getLoginUser().getId();
        int number = followUpService.getMyMonthFollowUpUser(userId);
        return success(number);
    }


    @GetMapping("/getMonthCjNumber")
    @Operation(summary = "业务员、权证当月已成交订单")
    public CommonResult<Integer> getMonthCjNumber() {
        //当前用户id
        Long userId = getLoginUser().getId();
        //查询所有跟进订单，获取订单号查询已成交额度
        List<UserFollowUpDO> followUpDOList = followUpService.getMonthFollowUpList(userId);
        int number = 0;
        if (followUpDOList.size()>0){
            for (UserFollowUpDO f : followUpDOList){
                int b = orderService.getMonthCjNumber(f.getApplicationId());
                number = number + b;
            }
        }
        return success(number);
    }

    @GetMapping("/getMonthCjMoney")
    @Operation(summary = "业务员、权证当月已成交金额")
    public CommonResult<BigDecimal> getMonthCjMoney() {
        //当前用户id
        Long userId = getLoginUser().getId();
        //查询所有跟进订单，获取订单号查询已成交额度
        List<UserFollowUpDO> followUpDOList = followUpService.getMonthFollowUpList(userId);
        BigDecimal sumMoney = new BigDecimal(0.00);
        if (followUpDOList.size()>0){
            for (UserFollowUpDO f : followUpDOList){
                BigDecimal b = orderService.getMonthCjMoney(f.getApplicationId());
                if(b!=null){
                    sumMoney = sumMoney.add(b);
                }
            }
        }
        return success(sumMoney);
    }

    @GetMapping("/salesman/getSalesmanInfos")
    @Operation(summary = "首页-业务员详情")
    @Parameter(name = "id", description = "业务员id", required = true, example = "1024")
    @PermitAll
    public CommonResult<SalesmanInfosResVo> getSalesmanInfos(@RequestParam("id") Long id) {
        SalesmanInfosResVo salesmanInfos = miniUserService.getSalesmanInfos(id);
        return success(salesmanInfos);
    }


    @PostMapping("/salesmanAddUser")
    @Operation(summary = "业务员-导入用户")
    public CommonResult<Boolean> salesmanAddUser(@Valid @RequestBody UserAddReqsVo reqVo) {
        miniUserService.salesmanAddUser(reqVo);
        return success(true);
    }


    @PostMapping("/updateUserInfo")
    @Operation(summary = "修改个人资料")
    public CommonResult<Boolean> updateUserInfo(@Valid @RequestBody UserAddReqsVo reqVo) {
        miniUserService.updateUserInfo(reqVo);
        return success(true);
    }

    @PostMapping("/mini-app-login")
    @PermitAll
    @Operation(summary = "临时获取登录-微信小程序的一键登录")
    public CommonResult<AuthLoginRespVo> weixinMiniAppLogin(Long userId) {
        return success(miniUserService.weixinMiniAppLogin(userId));
    }


    @GetMapping("/getPublicitySelectListByTypesName")
    @Operation(summary = "获得公示表类目")
    public CommonResult<List<PublicitySelectBaseVO>> getPublicitySelectListByTypesName(String typesName,Long orderId) {
        List<PublicitySelectBaseVO> list = publicityTypeService.getPublicitySelectListByTypesName(typesName,orderId);
        return success(list);
    }

    @GetMapping("/getPublicitySelectListByClassName")
    @Operation(summary = "获得公示表类目值选项")
    public CommonResult<List<PublicitySelectBaseVO>> getPublicitySelectListByClassName(String className, String typesName) {
        List<PublicitySelectBaseVO> list = publicityTypeService.getPublicitySelectListByClassName(className,typesName);
        return success(list);
    }


    @GetMapping("/my/property")
    @Operation(summary = "用户-已添加的资产")
    public CommonResult<List<PropertyResVo>> getMyProperty() throws Exception {
        //当前用户id
        Long userId = getLoginUser().getId();
        List<PropertyResVo> resVO = miniUserService.getMyProperty(userId);
        return success(resVO);
    }


    @GetMapping("/my/checkUserData")
    @Operation(summary = "用户-马上测额度-检查资料是否已填写")
    public CommonResult<String> getCheckProductInfo(String productTypeId) throws Exception {
        //当前用户id
        Long userId = getLoginUser().getId();
        if (StringUtils.isEmpty(productTypeId)){
            return success("");
        }else {
            CommonResult<String> result = miniUserService.getCheckProductInfo(userId,productTypeId);
            return result;
        }
    }


    @GetMapping("/my/getCheckProductAccess")
    @Operation(summary = "用户-马上测额度-产品准入匹配")
    public CommonResult<List<ProductAccessResVO>> getCheckProductAccess(String orderId) throws Exception {
        //当前用户id
        List<ProductAccessDO> list = miniUserService.getCheckProductAccess(orderId);
        return success(ProductAccessConvert.INSTANCE.convertLists(list));
    }

    @PostMapping("/allocationAgent")
    @Operation(summary = "订单设置-业务员")
    public CommonResult<Boolean> allocationAgent(@Valid @RequestBody UserAllocationReqVo reqVo) {
        miniUserService.updateUserAllocationAgent(reqVo);
        return success(true);
    }


    @PostMapping("/update/idCard")
    @Operation(summary = "业务员-完善身份证号")
    public CommonResult<Boolean> updateIdCard(@Valid @RequestBody UpdateIdCardReqVO reqVo) {
        //当前用户id
        Long userId = getLoginUser().getId();
        return success(miniUserService.updateIdCard(userId,reqVo));
    }



    @GetMapping("/flag/getCheckFinanceFlag")
    @Operation(summary = "是否开启-金融模块")
    @PermitAll
    public CommonResult<Boolean> getCheckFinanceFlag() {
        //当前用户id
        boolean flag = miniUserService.getCheckFinanceFlag();
        return CommonResult.success(flag);
    }


}
